const express = require('express');
const bodyParser = require('body-parser');
const mongodb = require('mongodb');
const { MongoClient, ObjectId } = mongodb;
const dbUrl = 'mongodb://localhost:27017';
const app = express();
app.use(bodyParser.json());

function getSingers() {
    return new Promise((resolve, reject) => {
        MongoClient.connect(dbUrl, { useNewUrlParser: true }, (err, client) => {
            if (err) {
                reject(err);
                return;
            }
            let miguDB = client.db('migu');
            let singerCollections = miguDB.collection('singer');
            singerCollections.find({}).toArray((err, result) => {
                if (err) {
                    reject(err);
                    return;
                }
                // console.log(result)
                client.close();
                resolve(result);
            })
        })
    })
}


function getRanklistPage(pageNo, pageSize) { //分页
    return new Promise((resolve, reject) => {
        MongoClient.connect(dbUrl, { useNewUrlParser: true }, (err, client) => {
            if (err) {
                reject(err);
                return;
            }
            let miguDB = client.db('migu');
            let singerCollections = miguDB.collection('ranklist');
            singerCollections.find({}).skip(pageNo * pageSize).limit(pageSize).toArray((err, result) => {
                if (err) {
                    reject(err);
                    return;
                }
                // console.log(result)
                client.close();
                setTimeout(function() {
                    resolve(result);
                }, 2000)

            })
        })
    })
}

app.get('/music/getSinger', async function(req, res) {
    let singers = [];
    let status = 1000;
    let msg = 'ok';
    try {
        singers = await getSingers()
    } catch (e) {
        status = 1005;
        msg = e.message;
    }
    res.send({
        status,
        msg,
        data: {
            singers
        }
    })
})


app.get('/music/getRanklistPage', async function(req, res) {

    let pageNo = Number(req.query.pageNo);
    let pageSize = Number(req.query.pageSize);

    let ranklist = [];
    let status = 10000;
    let msg = 'ok';
    try {
        ranklist = await getRanklistPage(pageNo, pageSize);
    } catch (e) {
        status = 10005;
        msg = e.message;
    }
    res.send({
        status,
        msg,
        data: {
            ranklist
        }
    })
});













app.listen(4000, function(err) {
    if (err) {
        return console.log(err);
    }
    console.log('正在监听4000端口')
})